package com.demo.security.sign;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**
 * 数字签名：JDK自带实现
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/17 13:21
 */
public class JDKSign {

    /**
     * MD5withRSA签名
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] signMD5withRSA(byte[] content, PrivateKey privateKey) throws Exception {
        return sign(content,privateKey,"MD5withRSA");
    }

    /**
     * MD5withRSA校验
     * @param content
     * @param sign
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static boolean verifyMD5withRSA(byte[] content, byte[] sign, PublicKey publicKey) throws Exception {
        return verify(content,sign,publicKey,"MD5withRSA");
    }

    /**
     * SHA1withRSA签名
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] signSHA1withRSA(byte[] content, PrivateKey privateKey) throws Exception {
        return sign(content,privateKey,"SHA1withRSA");
    }

    /**
     * SHA1withRSA校验
     * @param content
     * @param sign
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static boolean verifySHA1withRSA(byte[] content, byte[] sign, PublicKey publicKey) throws Exception {
        return verify(content,sign,publicKey,"SHA1withRSA");
    }

    /**
     * 签名
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] sign(byte[] content, PrivateKey privateKey,String type) throws Exception {
        Signature signature = Signature.getInstance(type);
        signature.initSign(privateKey);
        signature.update(content);
        return signature.sign();
    }

    /**
     * 校验
     * @param content
     * @param sign
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] content, byte[] sign, PublicKey publicKey,String type) throws Exception {
        Signature signature = Signature.getInstance(type);
        signature.initVerify(publicKey);
        signature.update(content);
        return signature.verify(sign);
    }

}
